//
//  JHAblumViewController.m
//  Liberty Voice
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ClearLove. All rights reserved.
//

#import "JHAblumViewController.h"
#import "JHAblumTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "JHUserViewController.h"
#import "JHAboutAblumTableViewCell.h"
#import "JHAblum.h"
#import "NetwordHandler.h"
#import "JHAboutAblum.h"

@interface JHAblumViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)UITableView *AblumTableView;
@property(nonatomic,retain)UITableView *aboutTableView;
@property(nonatomic,retain)UIView *ablumView;
@property(nonatomic,retain)UIScrollView *aboutScroll;
@property(nonatomic,retain)UIView *view1;
@property(nonatomic,retain)UIView *view2;
@property(nonatomic,retain)UIView *view3;
@property(nonatomic,retain)UISegmentedControl* Segmented;
@property(nonatomic,retain)NSMutableArray *ablumArr;
@property(nonatomic,retain)NSMutableDictionary *ablumDic;

@property(nonatomic,retain)NSMutableArray *aboutArr;
@end

@implementation JHAblumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dbManager = [JHDataBaseManager shareInstance];
    [self.dbManager openDB];
    // Do any additional setup after loading the view.
    [self dian];
        self.ablumArr = [NSMutableArray array];
    self.nextCursor = 1;
    [self getData];
    
//    [self createAbout];
    
    [self craetview];
    [self createaboutScroll];
    [self createAblum];

}
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block JHAblumViewController *vc = self;
    
    // 添加下拉刷新头部控件
    [self.AblumTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:1];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.AblumTableView headerBeginRefreshing];
    
}
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block JHAblumViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.AblumTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:(vc.nextCursor++) + 1];//请求更多数据
        
    }];
}
- (void)GetPersonList:(NSInteger)nextCursor
{
    /**
     *  获取列表数据
     */
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/15",self.albumId,nextCursor];
    NSLog(@"%@",str);
    [NetwordHandler requestWithURL:str completion:^(id result) {
        
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.ablumArr removeAllObjects];
        }

        NSDictionary *d = result;

        NSMutableArray *a = [[d objectForKey:@"tracks"] objectForKey:@"list"];
        for (NSDictionary *aaa in a) {
            JHAblum *ablum = [[JHAblum alloc] initWithDic:aaa];
            [_ablumArr addObject:ablum];
//            NSLog(@"111111111111%@",ablum.uid);
        }
        
        [self.AblumTableView headerEndRefreshing];
        [self.AblumTableView footerEndRefreshing];
        [self.AblumTableView reloadData];
        
    }];
    
}
- (void)getData
{
    /**
     *  个人信息
     */
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",self.albumId];
    [NetwordHandler requestWithURL:str completion:^(id result) {
        NSDictionary *d = result;
        
        self.ablumDic = [d objectForKey:@"album"];
        NSLog(@"%@",_ablumDic);
        [self createTable];
        [self createjianjie];

         }];
    [self.indicatorView removeFromSuperview];
}


- (void)GetPerson
{
    /**
     *  相关专辑
     */
    NSString *s = [NSString stringWithFormat:@"http://ar.ximalaya.com/rec-association/recommend/album/by_album?albumId=%@&device=android",self.albumId];
    [NetwordHandler requestWithURL:s completion:^(id result) {
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.aboutArr removeAllObjects];
        }

        NSMutableDictionary *d = result;
        self.aboutArr = [NSMutableArray array];
        NSMutableArray *a = [d objectForKey:@"albums"];
        for (NSDictionary *about in a) {
            JHAboutAblum *a = [[JHAboutAblum alloc] initWithDic:about];
            [_aboutArr addObject:a];
            
        }


        [self createAbout];
    }];
}
- (void)craetview
{
    //  上面的View
    self.ablumView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 170)];
    _ablumView.backgroundColor = [UIColor lightTextColor];
    [self.view addSubview:_ablumView];
    [_ablumView release];
    self.Segmented = [[UISegmentedControl alloc] initWithItems:@[@"简介", @"列表",@"相关专辑"]];
    _Segmented.frame = CGRectMake(10, _ablumView.frame.size.height - 30, self.view.frame.size.width - 20, 30);
    _Segmented.selectedSegmentIndex = 0;
    [_Segmented addTarget:self action:@selector(segmenAction:) forControlEvents:UIControlEventValueChanged];
    [_ablumView addSubview:_Segmented];
    [_Segmented release];
}
- (void)segmenAction:(UISegmentedControl *)seg
{
    //分段控制器点击方法
    if (seg.selectedSegmentIndex == 0) {
        _aboutScroll.contentOffset = CGPointMake(0, 0);
    }else
        if (seg.selectedSegmentIndex == 1) {
            [self addHeader];
            [self addFooter];
            _aboutScroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
            
        }else
            if (seg.selectedSegmentIndex == 2) {
                [self GetPerson];
                
                _aboutScroll.contentOffset = CGPointMake(self.view.frame.size.width * 2, 0);
            }
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    // 位移量
////    if (scrollView.contentOffset = CGPointMake(0, 0)) {
////        _Segmented.selectedSegmentIndex = 0;
////    }
////    else (scrollView.contentOffset == CGPointMake(self.view.frame.size.width, 0) ) {
////        [self addHeader];
////        [self addFooter];
////        _Segmented.selectedSegmentIndex = 1;
////
////    }else
////    {
////        [self GetPerson];
////       _Segmented.selectedSegmentIndex = 2;
////    }
//    
//}
- (void)createaboutScroll
{
    //  创建滚动视图
    self.aboutScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,_ablumView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - _ablumView.frame.size.height)];
    _aboutScroll.contentSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.size.height - _ablumView.frame.size.height);
    _aboutScroll.pagingEnabled = YES;
    _aboutScroll.bounces = NO;
    _aboutScroll.scrollEnabled = NO;
    _aboutScroll.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_aboutScroll];
    
    /**
     创建View
     
     :returns: 把View分别加入scroll中
     */
    self.view1 = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, _aboutScroll.frame.size.height)] autorelease];
//    _view1.backgroundColor = [UIColor yellowColor];
    [_aboutScroll addSubview:_view1];
    
    self.view2 = [[[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, _aboutScroll.frame.size.height)] autorelease];
    [_aboutScroll addSubview:_view2];

    self.view3 = [[[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, _aboutScroll.frame.size.height)] autorelease];
    [_aboutScroll addSubview:_view3];

}
- (void)createjianjie
{
     UIScrollView *Scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, _view1.frame.size.height - 130)];
    
//    Scroll.bounces = NO;
//    NSLog(@"%lf",_audioTableView.contentSize.height);
    /**
     简介界面
     
     :returns: 创建
     */
    UILabel *AblumName = [[[UILabel alloc] initWithFrame:CGRectMake(20, 20, 90, 30)] autorelease];
    AblumName.text = @"专辑名称:";
    [Scroll addSubview:AblumName];
    UILabel *AblumName1 = [[[UILabel alloc] initWithFrame:CGRectMake(AblumName.frame.size.width + 10, 20, self.view.frame.size.width - AblumName.frame.size.width - 20, 30)] autorelease];
    AblumName1.text = [_ablumDic objectForKey:@"title"];
    [Scroll addSubview:AblumName1];
    
    UILabel *Ablumperson = [[[UILabel alloc] initWithFrame:CGRectMake(AblumName.frame.origin.x , AblumName.frame.origin.y +30, 90, 30)] autorelease];
    Ablumperson.text = @"创建人:";
    [Scroll addSubview:Ablumperson];
    UILabel *Ablumperson1 = [[[UILabel alloc] initWithFrame:CGRectMake(AblumName.frame.size.width + 10, AblumName.frame.origin.y+ 30, self.view.frame.size.width - Ablumperson.frame.size.width - 20 , 30)] autorelease];
    Ablumperson1.text = [_ablumDic objectForKey:@"nickname"];
    [Scroll addSubview:Ablumperson1];
    
    UILabel *Ablumbiaoqian = [[[UILabel alloc] initWithFrame:CGRectMake(Ablumperson.frame.origin.x , Ablumperson.frame.origin.y +30, 90, 30)] autorelease];
    Ablumbiaoqian.text = @"标签:";
    [Scroll addSubview:Ablumbiaoqian];
    
    UILabel *Ablumbian = [[[UILabel alloc] initWithFrame:CGRectMake(Ablumbiaoqian.frame.size.width + 10, Ablumperson.frame.origin.y  + 30,  self.view.frame.size.width - Ablumbiaoqian.frame.size.width - 20, 30)] autorelease];
    Ablumbian.text = [_ablumDic objectForKey:@"tags"];
    [Scroll addSubview:Ablumbian];
    
    UILabel *AblumJianjie = [[[UILabel alloc] initWithFrame:CGRectMake(Ablumbiaoqian.frame.origin.x, Ablumbiaoqian.frame.origin.y + 30, 90, 30)] autorelease];
    AblumJianjie.text = @"简介:";
    
    [Scroll addSubview:AblumJianjie];
    UILabel *AblumJianjie1 = [[[UILabel alloc] init] autorelease];
//    AblumJianjie1.backgroundColor = [UIColor redColor];
    AblumJianjie1.text = [_ablumDic objectForKey:@"intro"];
    AblumJianjie1.numberOfLines = 0;
    CGFloat f = [[self class] heightWithText:[_ablumDic objectForKey:@"intro"]];
    AblumJianjie1.font = [UIFont systemFontOfSize:16];
    AblumJianjie1.frame = CGRectMake(Ablumbian.frame.origin.x, Ablumbiaoqian.frame.origin.y + 30,  self.view.frame.size.width - AblumJianjie.frame.size.width - 20, f + 90);
    [Scroll addSubview:AblumJianjie1];
    Scroll.delegate = self;
    [Scroll setContentSize:CGSizeMake(Scroll.frame.size.width, AblumJianjie1.frame.origin.y + AblumJianjie1.frame.size.height)];
    [_view1 addSubview:Scroll];

//    Scroll.contentOffset = CGPointMake(0, self.view.frame.size.height/3 +f + 40 );
}
+ (CGFloat)heightWithText:(NSString *)text
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
    CGSize size = CGSizeMake(250, 1000);
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

- (void)createAblum
{
    //  列表
    self.AblumTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _view2.frame.size.width, _view2.frame.size.height - 110) style:UITableViewStyleGrouped];
    _AblumTableView.delegate = self;
    _AblumTableView.dataSource = self;
    [_AblumTableView registerClass:[JHAblumTableViewCell class] forCellReuseIdentifier:@"ablum"];
    [_view2 addSubview:_AblumTableView];
}

- (void)createAbout
{
    // 相关专辑
    self.aboutTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _view3.frame.size.width, _view3.frame.size.height - 110) style:UITableViewStylePlain];
    _aboutTableView.delegate = self;
    _aboutTableView.dataSource = self;
    [_aboutTableView registerClass:[JHAboutAblumTableViewCell class] forCellReuseIdentifier:@"about"];
    [_view3 addSubview:_aboutTableView];
}

- (void)createTable
{
    //  个人信息
    UIImageView *touxiang = [[[UIImageView alloc] init] autorelease];
    [touxiang sd_setImageWithURL:[NSURL URLWithString:[_ablumDic objectForKey:@"coverLarge"]]];
    touxiang.frame = CGRectMake(20, 20, self.view.frame.size.width / 7 * 2, self.view.frame.size.width / 7 * 2);
    [_ablumView addSubview:touxiang];
    //  小头像部分
    UIImageView *touxiang2 = [[[UIImageView alloc] init] autorelease];
    touxiang2.layer.cornerRadius = 24.5;
    touxiang2.layer.masksToBounds = YES;
    [touxiang2 sd_setImageWithURL:[NSURL URLWithString:[_ablumDic objectForKey:@"avatarPath"]]];
    touxiang2.frame = CGRectMake(touxiang.frame.size.width + 35, 20, self.view.frame.size.width / 7, self.view.frame.size.width / 7);
    [_ablumView addSubview:touxiang2];
    
    UILabel *touxianglable = [[UILabel alloc] initWithFrame:CGRectMake(touxiang2.frame.origin.x + self.view.frame.size.width / 7 + 10, touxiang2.frame.origin.y + touxiang2.frame.size.width / 2 ,self.view.frame.size.width - touxiang2.frame.size.width - touxiang.frame.size.width - 10, 30)];
    touxianglable.text = [_ablumDic objectForKey:@"nickname"];
    touxianglable.font = [UIFont systemFontOfSize:15];
    [_ablumView addSubview:touxianglable];
    UIButton *b1 = [UIButton buttonWithType:UIButtonTypeSystem];
    b1.frame = CGRectMake(touxiang2.frame.origin.x , touxiang2.frame.origin.y ,self.view.frame.size.width - touxiang.frame.size.width - 10,touxiang2.frame.size.width);
//    b1.backgroundColor = [UIColor yellowColor];
    [b1 addTarget:self action:@selector(bAction) forControlEvents:UIControlEventTouchUpInside];
    [_ablumView addSubview:b1];
    UIImageView *a = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconfont-xiai"]]autorelease];
    a.frame = CGRectMake(b1.frame.origin.x, b1.frame.origin.y + touxiang2.frame.size.height + 20, 15, 15);
    [_ablumView addSubview:a];
    UIButton *d = [UIButton buttonWithType:UIButtonTypeSystem];
    d.frame = CGRectMake(a.frame.origin.x + 20, a.frame.origin.y, 50, 15);
    [d setTitle:@"收藏" forState:UIControlStateNormal];
    d.tag = 1000;
    [d addTarget:self action:@selector(shoucang:) forControlEvents:UIControlEventTouchUpInside];
    [_ablumView addSubview:d];
    
}
- (void)shoucang:(UIButton *)b
{
    //  收藏方法
    self.dbManager = [JHDataBaseManager shareInstance];
    if (b.tag == 1000) {
        [b setTitle:@"已收藏" forState:UIControlStateNormal];
        
        //  打开数据ku
        [_dbManager openDB];
        //  创建表
        [_dbManager createTable];
        self.a = [[JHAudio alloc] init];
        _a.title = [_ablumDic objectForKey:@"title"];
        _a.albumId = [_ablumDic objectForKey:@"albumId"];
        [_dbManager insertInfoWithlanou:_a];
        b.tag = 2000;
    }else
        if (b.tag == 2000) {
            //  创建数据库单例对象
            //        JHDataBaseManager *dbManager = [JHDataBaseManager shareInstance];
            //  打开数据ku
            [_dbManager openDB];
            //  创建表
            [_dbManager createTable];
            NSLog(@"%@",_a.albumId);
            [_dbManager  deleteInfoWithNum:[_a.albumId integerValue]];
            [b setTitle:@"收藏" forState:UIControlStateNormal];
            b.tag = 1000;
        }

}
- (void)bAction
{
    //  用户界面
    JHUserViewController *u = [[JHUserViewController alloc] init];
    u.str = [[_ablumDic objectForKey:@"uid"] description];
    NSLog(@"%@",[_ablumDic objectForKey:@"uid"]);
    [self.navigationController pushViewController:u animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //  行数
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _AblumTableView) {
        return _ablumArr.count;
    }else
        if (tableView == _aboutTableView) {
            return _aboutArr.count;
        }return 0;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //  重用池
    if (tableView == _AblumTableView) {
        
        JHAblumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ablum"];
        cell.ablum = _ablumArr[indexPath.section];
        return cell;
    }else
        if (tableView == _aboutTableView) {
            JHAboutAblumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"about"];
            cell.about = _aboutArr[indexPath.section];
            [cell.aboutButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            NSArray *arr = [self.dbManager selectInfo];
            [cell.aboutButton setTitle:@"收藏" forState:UIControlStateNormal];
            for (JHAudio *audio in arr) {
                if ([[audio.albumId description] isEqualToString:[cell.about.albumId description]]) {
                    [cell.aboutButton setTitle:@"已收藏" forState:UIControlStateNormal];
                    [cell.aboutButton removeTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
                    [cell.aboutButton addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside];
                }
            }
            cell.aboutButton.tag = indexPath.section + 1000;
            
            return cell;
            
        }
    return nil;
}

- (void)buttonAction:(UIButton *)button
{
    NSLog(@"点击的第%ld个按钮", button.tag - 1000);
    JHAboutAblum *about = _aboutArr[button.tag - 1000];
    
    [self.dbManager createTable];
    JHAudio *audio = [[JHAudio alloc] init];
    audio.albumId = about.albumId;
    audio.title = about.title;
    [self.dbManager insertInfoWithlanou:audio];
    [button setTitle:@"已收藏" forState:UIControlStateNormal];
    [self.aboutTableView reloadData];
}

- (void)buttonAction1:(UIButton *)button
{
    [button setTitle:@"收藏" forState:UIControlStateNormal];
    JHAboutAblum *about = _aboutArr[button.tag - 1000];
    [self.dbManager deleteInfoWithNum:[[about.albumId description] integerValue]];
    [self.aboutTableView reloadData];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 点击方法
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView == _AblumTableView) {
        JHPlayViewController *pl = [JHPlayViewController sharePlayerController];
        
        JHgequ *a = [[JHgequ alloc] init];
        a.title = [_ablumArr[indexPath.section]title];
        a.playPath32 = [_ablumArr[indexPath.section]playUrl32];
        [pl setStr:a];
        [pl beginAction:self];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"zhuan" object:@"jiaqing" userInfo:@{@"lol":@"666"}];
        [self presentViewController:pl animated:YES completion:^{
            
        }];
    }else
        if (tableView == _aboutTableView) {
            JHAblumViewController *c = [[JHAblumViewController alloc] init];
            c.albumId = [_aboutArr[indexPath.section] albumId];
            [self.navigationController pushViewController:c animated:YES];
        }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //  行高
    if (tableView == _AblumTableView) {
        return 110;
    }else
        if (tableView == _aboutTableView) {
            return 64;
        }return 0;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - ScrollView Delegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}

@end
